package com.grp6.game.ui.platform.text.ansi;

import java.io.PrintStream;

public class ColorPrinter{
	private PrintStream out;
	private Color background,foreground;
	private Boolean light;
	boolean stateFlushed = false;

	public ColorPrinter(PrintStream out) {
		this.out = out;
	}
	
	public ColorPrinter bg(Color color){
		this.background = color;
		stateFlushed = false;
		return this;
	}
	
	public ColorPrinter fg(Color color,Boolean light){
		this.light = light;
		this.foreground = color;
		stateFlushed = false;
		return this;
	}
	
	public ColorPrinter fg(Color color){
		return fg(color,null);
	}
	
	public ColorPrinter moveTo(int x,int y){
		out.print("\033["+x+";"+y+"H");
		return this;
	}
	
	public ColorPrinter rewind(){
		out.print("\033[2J");
		return moveTo(0,0);
	}
	
	public ColorPrinter reset(){
		out.print("\033[0;00m");
		stateFlushed = true;
		background = null;
		foreground = null;
		return this;
	}
	
	private void flushState(){
		if (foreground!=null)
			out.print("\033["+(light!=null&&light?"1":"0")+";3"+foreground.code+"m");
		if (background!=null)
			out.print("\033["+"4"+background.code+"m");
		stateFlushed = true;
	}
	
	public void println(String string){
		if (!stateFlushed)
			flushState();
		out.println(string);
	}
	
	public void print(String string){
		if (!stateFlushed)
			flushState();
		out.print(string);
	}
	
	public void print(char _char){
		if (!stateFlushed)
			flushState();
		out.print(_char);
	}
}
